package hasthi.tools;

import hasthi.common.BaseContext;
import hasthi.common.ComponetFactory;
import hasthi.common.HasthiException;
import hasthi.common.constants.WSDMConstants;
import hasthi.container.MessageContext;
import hasthi.container.SimpleMessageContext;
import hasthi.container.SoapContainer;
import hasthi.container.XsulBasedSoapContainer;

import java.io.StringReader;
import java.util.Arrays;

import org.xmlpull.v1.builder.XmlElement;

import xsul.XmlConstants;
import xsul.invoker.soap_over_http.SoapHttpDynamicInfosetInvoker;
import xsul.wsdl.WsdlDefinitions;
import xsul.wsif.WSIFService;
import xsul.wsif.WSIFServiceFactory;
import xsul.wsif_xsul_soap_gsi.Provider;
import xsul.wsif_xsul_soap_http.XsulSoapPort;
import xsul.xwsif_runtime.WSIFClient;
import xsul.xwsif_runtime.XmlBeansWSIFRuntime;
import edu.indiana.extreme.wsdm.ShutDownRequestDocument;
import edu.indiana.extreme.wsdm.ShutDownRequestDocument.ShutDownRequest;

public class XSULUtils {
public static void main(String[] args) throws HasthiException {
    XsulBasedSoapContainer container = (XsulBasedSoapContainer) ComponetFactory
    .createSoapContianier(new BaseContext(), null);
    ShutDownRequestDocument requestDocument = ShutDownRequestDocument.Factory.newInstance();
    ShutDownRequest shutDownRequest = requestDocument.addNewShutDownRequest();
    MessageContext message = new SimpleMessageContext(shutDownRequest,"https://129.79.246.253:6666/xregistry",
                WSDMConstants.ACTION_SHUTDOWN);
    container.sendReceive(message);
    System.out.println("Completed");
    
    for(StackTraceElement[] st:Thread.getAllStackTraces().values()){
        System.out.println(Arrays.toString(st));    
    }
    
}


    public static WSIFClient createWSIFClient(BaseContext baseContext,
            String serviceURL) throws HasthiException {
        WSIFClient client;
        if (serviceURL.startsWith("https")) {
            SoapHttpDynamicInfosetInvoker invoker = SoapContainer.createSecureInvoker(baseContext, null);
            String wsdlAsStr = invoker.invokeHttpGet(serviceURL);
            // System.out.println(wsdlAsStr);
            XmlElement el = XmlConstants.BUILDER
                    .parseFragmentFromReader(new StringReader(wsdlAsStr));
            WsdlDefinitions def = new WsdlDefinitions(el);
            WSIFServiceFactory wsf = WSIFServiceFactory.newInstance();
            WSIFService serv = wsf.getService(def);
            serv.addLocalProvider(new Provider(invoker));
            client = XmlBeansWSIFRuntime.getDefault().newClientFor(serv.getPort());
            ((XsulSoapPort) client.getPort()).setInvoker(invoker);
        } else {
            client = XmlBeansWSIFRuntime.newClient(serviceURL);
        }
        return client;
    }
}
